/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年12月08日
*   版    本：v1.0.0
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
* ================================================================*/


#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        vector<int> res;
        int size = arr.size();
        
        int start = 0, end = size - 1;
        int index = 0;
        while( start < end ){
            index = (end - start)/2 + start;
            if(arr[index] > x){
                end--;
            }else if( arr[index] < x ){
                start++;
            }else {
                break;
            }
        }

        int high = index+k <= size - 1? index+k:size - 1;
        int low = index - k >= 0? index - k:0;

        while(high - low >= k){
            if(x - arr[low] > arr[high] - x){
                low++;
            }else{
                high--;
            }
        }

        for(int i = low; i <= high; i++){
            res.push_back(arr[i]);
        }

        return res;
    }
};